import { Injectable, Logger } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { RedisService } from 'nestjs-redis'
import { IResponse } from 'src/interface/response.interface'
import { IUserProject, User } from 'src/interface/user.interface'
import * as Redis from 'ioredis'

const logger = new Logger('user.service')

@Injectable()
export class UserService {
    private response: IResponse
    private redis: Redis.Redis
    constructor(
        @InjectModel('USER_MODEL') private readonly userModel: Model<User>,
        private readonly redisService: RedisService
    ) {
        this.redis = this.redisService.getClient("management")
    }

    async regist(user: User) {
        return this.findOneByPhone(
            user.phone
        ).then((res: []) => {
            if (res.length !== 0) {
                // console.log('该用户已经注册')
                // throw Error('用户已注册')
                this.response = { code: 1, msg: '当前手机号已注册' }
                throw this.response
            }
        }).then(async () => {
            try {
                const createUser = new this.userModel(user)
                await createUser.save()
                this.response = { code: 0, msg: '用户注册成功!' }
                return this.response
            } catch (error) {
                this.response = { code: 1, msg: '用户注册失败，请联系相关负责人，错误详情' + error }
                throw this.response
            }
        }).catch(err => {
            logger.log(`${user.phone}:${err.msg}`)
            return this.response
        })
    }

    async alter(user: User) {
        return this.findOneByPhone(user.phone)
            .then(async () => {
                return await this.userModel.findOneAndUpdate({ phone: user.phone }, user, {}, () => {
                    logger.log(`用户${user.phone}修改成功!`)
                }).then(() => {
                    return this.response = { code: 0, msg: '用户修改成功' }
                })
            })
    }

    async findOneByPhone(phone: string) {
        return await this.userModel.find({
            phone
        })
    }

    async testRedis() {
        return await this.redis.set("management", "hello world")
    }

    async findOneByUserId(userId: string) {
        return await this.userModel.findById({
            _id: userId
        })
    }

    async addUserProject(projectId, userId){
        const user: User = await this.findOneByUserId(userId)
        const userProject: IUserProject = {
            projectId,
            identity: '项目经理'
        }
        user.projects.push(userProject)
        await this.userModel.findByIdAndUpdate(userId, user)
    }
}
